import requests
from python_ai.common.xcommon import *
import os
import json

dt = rand_name_on_now()
remoteFullPath = "/apps/网盘助手2021/" + dt + "_痔疮栓底方.jpg"
print('remoteFullPath:', remoteFullPath)
localFullPath = 'D:\\_dell7590_root\\tmp\\test\\upload\\痔疮栓底方.jpg'
print('localFullPath:', localFullPath)
localFileSize = os.path.getsize(localFullPath)

url = 'https://pan.baidu.com/rest/2.0/xpan/file?method=precreate'
data = {
    'path': remoteFullPath,
    'size': str(localFileSize),
    'isdir': '0',
    'autoinit': '1',
    'rtype': '0',
    # 'block_list': '["7281d3722954f3bd1fee0189e709020c","e04fdec77b8a443108c06530502323cb","654075f340b5a7868f1e037bdcdfa1ef","315e6d67e109ebf1b6061030ec28ba6b"]'
    'block_list': '["8f392d43abebd83288fd072185c0bc16","fd556e39c9665c31597a19f044062d0b"]'
}
params = {
    'access_token': '121.c8d953d5d6a1ba16d0795f54cc72c32d.YD11U9RAA-buAKn7hS5HrGhFfGtocls7uvKPcOD.wcgxEw'
}
headers = {
    'User-Agent': 'pan.baidu.com'
}
r = requests.post(url=url, data=data, params=params, headers=headers)
rjson = r.json()
print(rjson)
r.close()

uploadid = rjson['uploadid']
block_list = rjson['block_list']
print(uploadid)
print(block_list)

for blockIdx in block_list:
    sep(blockIdx)
    url = 'https://d.pcs.baidu.com/rest/2.0/pcs/superfile2?method=upload'
    data = {

    }
    files = [
        ('file', open(f'{localFullPath}.00{blockIdx}', 'rb'))
    ]
    params = {
        'access_token': '121.c8d953d5d6a1ba16d0795f54cc72c32d.YD11U9RAA-buAKn7hS5HrGhFfGtocls7uvKPcOD.wcgxEw',
        'method': 'upload',
        'type': 'tmpfile',
        'path': remoteFullPath,
        'uploadid': uploadid,
        'partseq': str(blockIdx),

    }
    headers = {
        'User-Agent': 'pan.baidu.com'
    }
    r = requests.post(url=url, data=data, params=params, headers=headers, files=files)
    print(f'|{r.text}|')
    # rjson = r.json()
    # print(rjson)
    r.close()

url = 'https://pan.baidu.com/rest/2.0/xpan/file?method=create'
data = {
    'path': remoteFullPath,
    'size': str(localFileSize),
    'isdir': '0',
    'rtype': '0',
    'uploadid': uploadid,
    'block_list': '["8f392d43abebd83288fd072185c0bc16","fd556e39c9665c31597a19f044062d0b"]',
}
params = {
    'access_token': '121.c8d953d5d6a1ba16d0795f54cc72c32d.YD11U9RAA-buAKn7hS5HrGhFfGtocls7uvKPcOD.wcgxEw'
}
headers = {
    'User-Agent': 'pan.baidu.com'
}
r = requests.post(url=url, data=data, params=params, headers=headers)
print(f'|{r.text}|')
rjson = r.json()
print(rjson)
r.close()